package com.onemile.app;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

import com.onemile.app.base.BaseUI;
import com.onemile.controls.AdpLV_CommodityList;
import com.onemile.controls.AdpLV_CouponList;
import com.onemile.data.DXml;
import com.onemile.data.DXml.FieldList;
import com.onemile.entity.MessageCode;
import com.onemile.entity.PubConst;
import com.onemile.entity.Session;
import com.onemile.entity.model.ECommodity;
import com.onemile.entity.model.ECoupon;
import com.onemile.net.NetClient;
import com.onemile.utils.UtiDialogsFactory;
import com.onemile.utils.UtiDialogsFactory.DialogCallBack;

public class UICouponList extends BaseUI
{

   private AdpLV_CouponList adpCoupon;

   // 分页需要的=========Begin==============================================
   /**
    * 存储已经加载的页码
    */
   private ListView listView;
   private ArrayList<Object> loadedPageList;
   private LayoutInflater mInflater;
   private View footLoadingView;
   private TextView txtNoData;
   private int MaxDateNum;// 设置一个最大的数据条数，超过即不再加载
   private int lastVisibleIndex; // 最后可见条目的索引
   private int nextPageNum = 1;

   // 分页需要的=========END==============================================

   private void InitControls()
   {
	  // 分页需要的=========Begin==============================================
	  mInflater = LayoutInflater.from(this);
	  footLoadingView = mInflater.inflate(R.layout.listview_moredata, null);
	  txtNoData = (TextView) mInflater.inflate(R.layout.all_no_data_txt, null);
	  loadedPageList = new ArrayList<Object>();
	  // 分页需要的=========END==============================================

	  listView = (ListView) findViewById(R.id.listView_coupon);
	  // 分页需要的=========Begin==============================================
	  listView.setOnScrollListener(scrollListener);
	  // 分页需要的=========End==============================================
	  listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
	  {
		 @Override
		 public void onItemClick(AdapterView<?> arg0, View currentView, int position, long arg3)
		 {
			if (listView.getFooterViewsCount() > 0 && position == listView.getAdapter().getCount() - 1)
			{
			   // 屏蔽掉FootView的单击事件
			}
			else
			{

			}
		 }
	  });
   }

   // 分页需要的=========Begin==============================================
   private OnScrollListener scrollListener = new OnScrollListener()
   {
	  @Override
	  public void onScrollStateChanged(AbsListView view, int scrollState)
	  {
	  }

	  @Override
	  public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
	  {
		 try
		 {
			lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
			if (visibleItemCount != 0)
			{
			   if ((firstVisibleItem + visibleItemCount) == totalItemCount)// 表示已经滚动到底部了
			   {
				  nextPageNum = totalItemCount / PubConst.Setting.GOODSLIST_NUM + 1;// 计算当前是第几页数据

				  if (listView.getFooterViewsCount() < 1)// 当没有其他数据加载时，再加载,确保同一时间只运行一个下载线程
				  {
					 if (!loadedPageList.contains(nextPageNum))// 如果没有加载当前页面
					 {
						executeAsyncTask(PubConst.TaskName.COUPON_LIST);
					 }
				  }
			   }
			}
		 }
		 catch (Exception e)
		 {
			Log.e(PubConst.Tag.ERROR, "UIFavorite_onScroll()", e);
		 }
	  }
   };

   // 分页需要的=========END==============================================
   @Override
   protected void onCreateOverride(Bundle savedInstanceState)
   {
	  SetNavigationStatus(3);
	  InitControls();
	  executeAsyncTask(PubConst.TaskName.COUPON_LIST);
   }

   @Override
   public int SetContentViewLayoutResId()
   {
	  return R.layout.coupon;
   }

   @Override
   public void SetTopToolbar(TextView topTxt, ImageView leftImBtn, ImageView rightImgBtn, RelativeLayout rightRay, TextView cartNum)
   {
	  topTxt.setText(getString(R.string.title_mycoupon));
	  leftImBtn.setVisibility(View.INVISIBLE);
	  rightRay.setVisibility(View.VISIBLE);
	  SetRightBtnToCart();
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if (taskName.equals(PubConst.TaskName.COUPON_LIST))
	  {
		 // 分页需要的=========Begin==============================================
		 listView.addFooterView(footLoadingView);
		 txtNoData.setVisibility(View.GONE);
		 if (listView.getChildCount() < 1)// 当列表不存在的时候才显示第一次加载的画面
		 {
			UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UICouponList.this, getString(R.string.dialog_loading));
			adpCoupon = new AdpLV_CouponList(UICouponList.this);
			listView.setAdapter(adpCoupon);
			listView.removeFooterView(footLoadingView);
		 }
		 // 分页需要的=========End==============================================
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if (taskName != null && taskName.equals(PubConst.TaskName.COUPON_LIST))
	  {
		 try
		 {
			return NetClient.GetCouponsByUserId_S(Session.getInstance().getUserInfo().getUserId(), nextPageNum, 10);
		 }
		 catch (Exception e)
		 {
			if (Session.getInstance().IsDEBUG())
			{
			   Log.e("ERROR", "UIConpon_onAsyncTaskInBackground(taskName, params) ", e);
			}
		 }
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  try
	  {
		 if (taskName.equals(PubConst.TaskName.COUPON_LIST))
		 {
			// 分页需要的=========Begin==============================================

			if (result != null)// 有结果
			{
			   DXml data = (DXml) result;
			   if (data.getHead().GetFieldValue("RspCode").equals(MessageCode.Success.Code))
			   {
				  ArrayList<ECoupon> list = new ArrayList<ECoupon>();
				  ECoupon coupon = null;
				  int size = data.getBody().getChilds().length;
				  for (int i = 0; i < size; i++)
				  {
					 FieldList fieldList = data.getBody().GetFieldList(i);

					 coupon = new ECoupon();
					 coupon.setCouponId(fieldList.GetFieldValue("CouponId"));
					 coupon.setCouponName(fieldList.GetFieldValue("CouponName"));
					 coupon.setCouponPrice(fieldList.GetFieldFloat("CouponPrice"));
					 coupon.setUsedTime(fieldList.GetFieldValue("UsedTime"));
					 coupon.setIsUsed(fieldList.GetFieldInt32("IsUsed"));
					 coupon.setStartDate(fieldList.GetFieldValue("StartDate"));
					 coupon.setEndDate(fieldList.GetFieldValue("EndDate"));

					 list.add(coupon);
				  }

				  adpCoupon.addItem(list);
				  adpCoupon.notifyDataSetChanged();
				  loadedPageList.add(nextPageNum);
			   }
			}
			else
			// 如果没有找到结果又是第一次加载数据。显示 无数据
			{
			   if (listView.getChildCount() < 1 || (listView.getChildCount() == 1 && listView.getFooterViewsCount() == 1))
			   {
				  txtNoData.setVisibility(View.VISIBLE);
			   }
			}
			// 第一次打开时显示
			if (listView.getChildCount() < 1 || (listView.getChildCount() == 1 && listView.getFooterViewsCount() == 1))
			{
			   UtiDialogsFactory.getInstance().DismissLoadingDialog();
			}
			if (listView.getFooterViewsCount() > 0)
			{
			   listView.removeFooterView(footLoadingView);
			}

			// 分页需要的=========End==============================================
		 }
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIConpon_onAsyncTaskEnd(taskId, taskName, params, result) ", e);
		 }
	  }
   }
}
